package timing.ukulele.gateway.filter;

import timing.ukulele.gateway.config.JwtProperties;
import timing.ukulele.gateway.utils.JWTUtil;
import timing.ukulele.common.Constant;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

public class JwtTokenAuthenticationFilter implements WebFilter {
    private final JwtProperties jwtProperties;

    public JwtTokenAuthenticationFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String token = resolveToken(exchange.getRequest());
        try {
            if (StringUtils.hasText(token)) {
                Authentication authentication = JWTUtil.getAuthentication(token, jwtProperties.getSecretKey());
                if (authentication != null)
                    return chain.filter(exchange)
                            .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

    private String resolveToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(Constant.TOKEN);
        if (StringUtils.hasText(token)) {
            return token;
        }
        return null;
    }
}